import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormTextArea, ProFormSwitch } from '@ant-design/pro-components';
import { Card, message } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import tenantService from '../../services/tenants';
import { Tenant } from '../../types';

const TenantForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<Tenant>>();
  const isEdit = !!id;

  useEffect(() => {
    if (isEdit) {
      fetchTenant();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchTenant = async () => {
    try {
      const response = await tenantService.getTenant(Number(id));
      setInitialValues(response);
    } catch (error: any) {
      message.error('Failed to fetch tenant details');
      navigate('/tenants');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        name: values.name,
        description: values.description,
        tenantKey: values.tenantKey,
        isActive: values.isActive !== undefined ? values.isActive : true,
      };

      if (isEdit) {
        await tenantService.updateTenant(Number(id), payload);
        message.success('Tenant updated successfully');
      } else {
        await tenantService.createTenant(payload);
        message.success('Tenant created successfully');
      }
      navigate('/tenants');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'create'} tenant`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title={isEdit ? 'Edit Tenant' : 'Create Tenant'}>
      <ProForm
        initialValues={initialValues || { isActive: true }}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? 'Update' : 'Create',
          },
          resetButtonProps: {
            onClick: () => navigate('/tenants'),
          },
        }}
      >
        <ProFormText
          name="name"
          label="Tenant Name"
          placeholder="Enter tenant name"
          rules={[{ required: true, message: 'Please enter tenant name' }]}
        />

        <ProFormText
          name="tenantKey"
          label="Tenant Key"
          placeholder="Enter unique tenant key"
          rules={[
            { required: true, message: 'Please enter tenant key' },
            { pattern: /^[a-zA-Z0-9_-]+$/, message: 'Only letters, numbers, hyphens and underscores allowed' },
          ]}
          disabled={isEdit}
          tooltip={isEdit ? 'Tenant key cannot be changed after creation' : 'Unique identifier for the tenant'}
        />

        <ProFormTextArea
          name="description"
          label="Description"
          placeholder="Enter tenant description"
          fieldProps={{ rows: 4 }}
        />

        <ProFormSwitch
          name="isActive"
          label="Active"
          tooltip="Whether the tenant is active and can access the system"
        />
      </ProForm>
    </Card>
  );
};

export default TenantForm;
